const mongoose = require("mongoose");
const puppeteer = require("puppeteer");
const redis = require("../config/redis");
const { logger } = require("../config/utils"); 
const { redisKey } = require("../config/env");
// 主页
const host = "http://124.115.228.93";
// 详情页
const preModalLink = "http://124.115.228.93/zfrgdjpt/";
// 区域
const area = {
	// 长安
	"ca": "xmgsca.aspx",
	// 城6区
	"c6": "xmgs.aspx"
};

// 休息
const sleep = delay => new Promise(resolve => setTimeout(() => resolve(), delay));

// 更新链接
const updateLink = async (start, end, address) => {
	const key = redisKey.houseLinkInfo +  "_" + address;
	const House = mongoose.model("House");
	let houseLinks = {};
	try {
		const info = await redis.get(key);
		houseLinks = info ? JSON.parse(info) : {};
	} catch (error) {
		console.log(error.message);
		logger("task_house_link_error", error.stack);
		return;
	}
	puppeteer.launch({ headless: true, args: ["--no-sandbox", "--disable-setuid-sandbox"]}).then(async browser => {
		const url = `${host}/zfrgdjpt/${area[address]}`;
		console.log("****** 打开浏览器 ******");
		const page = await browser.newPage();
		await page.goto(url, { waitUntil: "networkidle0" });
		console.log("****** 进入列表页 ******");
		await page.waitForSelector("body .xmgsList");
		for (let m = start; m <= end; m++) {
			console.log(`****** 开始第${m}页 加载数据 ******`);
			if (m !== 1) {
				await page.goto(`${url}?page=${m}`, { waitUntil: "networkidle0" });
				try {
					await page.waitForSelector("body .xmgsList");
				} catch (error) {
					console.log(`****** 八成遇见验证码了,等三秒继续刚！ ****** \n ${error}`);
					await sleep(3000);
					await page.goto(`${url}?page=${m}`, { waitUntil: "networkidle0" });
					await page.waitForSelector("body .xmgsList");
				}
			}
			let linkDatas = await page.evaluate((preModalLink) => {
				const items = $(".xmgsItem");
				let links = [];
				for (let i = 0; i < items.length; i++) {
					if ($($(items[i]).find(".size21 .vm.mag_l10 .vm.mag_l10")[0]).text().indexOf("销售公告") > -1) {
						const attrStr = $($(items[i]).find(".size21 .vm.mag_l10 .vm.mag_l10")[0]).attr("onclick");
						if (attrStr) links.push(preModalLink + attrStr.split("content: '")[1].split("',")[0]);
					}
					if ($($(items[i]).find(".size21 .vm.mag_l10 .vm.mag_l10")[1]).text().indexOf("销售公告") > -1) {
						const attrStr = $($(items[i]).find(".size21 .vm.mag_l10 .vm.mag_l10")[1]).attr("onclick");
						if (attrStr) links.push(preModalLink + attrStr.split("content: '")[1].split("',")[0]);
					}
				}
				return links;
			}, preModalLink);

			for (let i = 0; i < linkDatas.length; i++) {
				let item = linkDatas[i];
				if (!houseLinks[item]) {
					try {
						await House.create({ link: item });
					} catch (error) {
						console.log("创建链接失败！" + error.message);
						logger("task_house_link_error", error.stack);
					}
					logger("task_house_link", `更新的链接: ${item}`);
					houseLinks[item] = "notUpdate";
				}
			}
			try {
				let result = await redis.set(key, JSON.stringify(houseLinks));
				if(result === "OK") {
					console.log(`****** 第${m}页 数据更新完毕 ******`);
				}else {
					console.log(`****** 第${m}页 数据更新失败 ****** ${result}`);
				}
			} catch (error) {
				logger("task_house_link_error", error.stack);
				console.log(`redis 保存失败！\n ${error.stack}`);
			}
			if (m !== 1) {
				const delay = parseInt(Math.random() * 5000 + 2000);
				console.log(`****** 延迟${delay / 1000} 秒 ******`);
				await sleep(delay);
			}
		}
		console.log("****** 所有链接加载完毕！ ******");
		await browser.close();
	}).catch(function (error) {
		console.log(error.message);
		logger("task_house_link_error", error.stack);
	});
};


module.exports = updateLink;




